import json
import time
import hmac
import hashlib
import base64
from urllib.parse import urlparse, urlencode
import websocket

from InterviewAgent.settings import XF_APPID, XF_API_SECRET, XF_API_KEY, XF_SPARK_ULTRA_API_HOST

# WebSocket endpoint derived from HTTP host
# e.g. if XF_SPARKX1_API_HOST = "https://spark-api.xf-yun.com/v1/chat"
# then WS URL is "wss://spark-api.xf-yun.com/v1/chat"
XF_WS_URL = XF_SPARK_ULTRA_API_HOST.replace("https://", "wss://")


class WsParam:
    def __init__(self):
        o = urlparse(XF_WS_URL)
        self.host = o.netloc
        self.path = o.path

    def create_url(self):
        date = time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime())
        sign_str = f"host: {self.host}\ndate: {date}\nGET {self.path} HTTP/1.1"
        sig = base64.b64encode(
            hmac.new(XF_API_SECRET.encode(), sign_str.encode(), hashlib.sha256).digest()
        ).decode()
        auth_str = (
            f'api_key="{XF_API_KEY}", algorithm="hmac-sha256", '
            f'headers="host date request-line", signature="{sig}"'
        )
        auth_b64 = base64.b64encode(auth_str.encode()).decode()
        params = {
            "authorization": auth_b64,
            "date": date,
            "host": self.host
        }
        return XF_WS_URL + "?" + urlencode(params)


def extract_parsedData_info_ws(text):
    result = {"content": ""}
    ws_param = WsParam()

    def on_message(ws, message):
        data = json.loads(message)
        header = data.get("header", {})
        if header.get("code") != 0:
            print("Error response:", data)
            result["error"] = data
            ws.close()
            return
        choices = data.get("payload", {}).get("choices", [])
        if choices:
            texts = choices["text"][0]["content"]
            chunk = "".join(texts) if isinstance(texts, list) else texts
            result["content"] += chunk
        if header.get("status") == 2:
            ws.close()

    def on_open(ws):
        # payload.message.text as list of {role, content}
        payload = {
            "header": {"app_id": XF_APPID, "uid": "user_001"},
            "parameter": {
                "chat": {
                    "domain": "lite",  # 或者 lite/search
                    "temperature": 0.5,
                    "max_tokens": 2048
                }
            },
            "payload": {
                "message": {
                    "text": [
                        {
                            "role": "user",
                            "content": text + "。请基于上述文本内容提取为结构化信息，字段统一使用中文，只返回干净的JSON格式"
                        }
                    ]
                }
            }
        }
        ws.send(json.dumps(payload))

    def on_error(ws, error):
        import traceback
        print("WebSocket error type:", type(error))
        print("WebSocket error:", error)
        traceback.print_exc()
        result["error"] = str(error)

    def on_close(ws, *args):
        print("WebSocket closed.")

    ws = websocket.WebSocketApp(
        ws_param.create_url(),
        on_open=on_open,
        on_message=on_message,
        on_error=on_error,
        on_close=on_close
    )

    # 保持心跳，避免断开
    ws.run_forever(ping_interval=30, ping_timeout=10)

    # print(result["content"])
    json_str_clean = result["content"].replace("```json", "").replace("```", "").strip()
    return json.loads(json_str_clean)

